package io.xxx.eva.robot.send;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import io.xxx.eva.exception.IPadSendMessageException;
import io.xxx.eva.receiver.Receiver;
import io.xxx.eva.task.TaskMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.core.annotation.Order;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Slf4j
@Order(1)
@Component
public class IPadSender implements Sender {

    private final RestTemplate restTemplate;

    public IPadSender(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.requestFactory(OkHttp3ClientHttpRequestFactory.class)
                .build();
    }

    @Override
    public void send(Receiver receiver, TaskMessage message) {
        log.debug("发送消息[receiver:{},message:{}]", JSON.toJSONString(receiver), JSON.toJSONString(message));
        JSONObject request = new JSONObject();
        request.put("receiver", JSON.toJSONString(receiver));
        request.put("message", JSON.toJSONString(message));
        ResponseEntity<Void> entity = restTemplate.postForEntity("url", request, Void.class);
        if (!entity.getStatusCode().is2xxSuccessful()) {
            throw new IPadSendMessageException();
        }
    }
}
